/**
 * This class processes all Vega spec customizations,
 * converting url object parameters into query results.
 */
export class EmsFileParser {

  constructor(serviceSettings) {
    this._serviceSettings = serviceSettings;
  }

  // noinspection JSMethodCanBeStatic
  /**
   * Update request object, expanding any context-aware keywords
   */
  parseUrl(obj, url) {
    if (typeof url.name !== 'string') {
      throw new Error(`data.url with {"%type%": "emsfile"} is missing the "name" of the file`);
    }
    // Optimization: so initiate remote request as early as we know that we will need it
    if (!this._fileLayersP) {
      this._fileLayersP = this._serviceSettings.getFileLayers();
    }
    return { obj, name: url.name };
  }

  /**
   * Process items generated by parseUrl()
   * @param {object[]} requests each object is generated by parseUrl()
   * @returns {Promise<void>}
   */
  async populateData(requests) {
    if (requests.length === 0) return;

    const layers = await this._fileLayersP;

    for (const { obj, name } of requests) {
      const foundLayer = layers.find(v => v.name === name);
      if (!foundLayer) {
        throw new Error(`emsfile ${JSON.stringify(name)} does not exist`);
      }
      obj.url = foundLayer.url;
    }
  }

}
